const setSchedule = require('../../tools/setSchedule')
const { DataTemplateModel } = require('../../models/models')

function setUserSchedule(info = {}) {
    const { deviceId, deviceSlaver, username } = info
    let templateIdList = []
    deviceSlaver.forEach(element => {
        templateIdList.push(element.templateId)
    });
    //如果有templateId
    if (templateIdList.length > 0) {
        return new Promise((res) => {
            DataTemplateModel.aggregate([{
                $match: {
                    $and: [{ username },
                    { templateId: { $in: templateIdList } }]

                }
            },
            {
                $project: {
                    children: 1,
                    templateId: 1,
                    _id: 0
                }
            },
            {
                $group: {
                    _id: '$templateId',
                    plcList: {
                        $addToSet: '$children.plc'
                    }
                },
            },
            {
                $unwind: "$plcList"
            }
            ]).then(docs => {
                deviceSlaver.forEach(sitem => {
                    const plcList = docs.find(ditem => ditem._id === sitem.templateId)
                    if (plcList) {
                        plcList.plcList.sort((a, b) => { return a * 1 - b * 1 })
                        const plc = plcList.plcList[0]
                        const len = plcList.plcList.length
                        //执行定时任务
                        //传入deviceId,slaverIndex,plc,time,len
                        const result = setSchedule.setUserSchedule(
                            {
                                deviceId,
                                slaverIndex: sitem.slaverIndex,
                                plc,
                                len,
                                time: sitem.frequency
                            })
                            res(result)
                    }else{
                        res({status:1,data:`plcList:${plcList}`})
                    }

                })
            })
        })


    }else{
        res({status:1,data:`templateList:${templateIdList.length}`})
    }



}

module.exports = setUserSchedule